package main

import (
	"os"
	"feedfinder"
	"text/template"
	"flag"
	"net/http"
	"log"
	"fmt"
	"sort"
)

var (
	default_path string = os.Getenv("HOME") + "/.gorss/feeds"

	host = flag.String("host", "localhost:8080", "output web view on specified host and port")
	web = flag.Bool("web", false, "start webserver")
	infile = flag.String("input", default_path, "path to feed config")

	feeds []string
)

const feed = `
{{.Title}}
	{{.Feed}}
	{{.Date}}
	{{.Link}}

	{{.Summary}}
`

const webfeedHeader = `
<html>
<title>GoRSS</title>
<body>
`

const webfeedFooter = `
</body>
</html>
`

const webfeed = `
	<div>
		<h2><a href="{{.Link}}">{{.Title}}</a></h2>
	</div>
	<div>
		<p>{{.Feed}}</p>
		<p>{{.Date}}</p>
	</div>
	<div>
		<p>{{.Summary}}</p>
	</div>
`

func main() {
	flag.Parse()

	log.SetFlags(log.Lshortfile)

	var err error
	feeds, err = FeedURLS(*infile)
	if err != nil {
		log.Fatalln(err)
	}

	if *web {
		http.HandleFunc("/", webHandler)
		log.Fatal(http.ListenAndServe(*host, nil))
	} else {			
		s := processFeeds()
		t := template.Must(template.New("feed").Parse(feed))
		for _, v := range s {
			err := t.Execute(os.Stdout, v)
			if err != nil {
				log.Fatalln(err)
			}
		}
	}
}	

func webHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, webfeedHeader)
	s := processFeeds()
	t := template.Must(template.New("webfeed").Parse(webfeed))
	for _, v := range s {
		err := t.Execute(w, v)
		if err != nil {
			log.Fatalln(err)
		}
	}
	fmt.Fprint(w, webfeedFooter)
}

func processFeeds() (stories feedfinder.Stories) {
	for _, url := range feeds {
		m, err := feedfinder.Feed(url)
		if err != nil {
			log.Fatalln(err)
		}

		s, err := feedfinder.FetchStories(m)
		if err != nil {
			log.Fatalln(err)
		}
		stories = append(stories, s...)
	}

	sort.Sort(stories)

	return stories
}
